<template>
    <el-form
      size="large"
      :rules="Rules"
      ref="userForm"
      :model="formData"
      label-width="100px"
    >
      <el-form-item prop="name" label="人员名称">
        <el-input clearable placeholder="请输入人员名称" v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item prop="logname" label="登录名">
        <el-input clearable placeholder="请输入登录名" v-model="formData.logName"></el-input>
      </el-form-item>
      <el-form-item prop="showOrder" label="人员排序">
        <el-input-number v-model="formData.showOrder" :step="5" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(userForm)">保存</el-button>
        <el-button type="info" @click="handleClose">关闭</el-button>
      </el-form-item>
    </el-form>
  </template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { UserBeanData, Rules } from '@/model/system/user/UserConstants'
import { loadUserById, saveUser, getMaxIndex } from '@/api/system/user/UserManager'
import { pinyin } from 'pinyin-pro'

const userForm = ref()
const emit = defineEmits(['close-dialog', 'reload-data'])
const props = defineProps({ fid: String, id: String })
const formData = ref({ ...UserBeanData, deptId: props.fid })

const handleClose = () => {
  emit('close-dialog')
}

const selectIcon = (item) => {
  formData.value.icon = item
}

watch(() => formData.value.name, (newValue, oldVlue) => {
  formData.value.logName = pinyin(newValue, { toneType: 'none' }).replace(/\s/g, '')
})

const submitForm = async (userForm) => {
  if (!userForm) return
  userForm.validate(valid => {
    if (valid) {
      saveUser(formData.value).then(() => {
        ElMessage({
          message: '保存成功!',
          type: 'success',
          duration: 800
        })
        emit('reload-data')
        emit('close-dialog')
      }).catch(() => {
        ElMessage.error('保存失败！')
      })
    }
  })
}

onMounted(() => {
  const id = props.id
  if (id) {
    loadUserById(id).then(data => {
      formData.value = { ...data }
    })
  } else {
    getMaxIndex(props.fid).then(data => {
      formData.value.showOrder = data + 5
    })
  }
})
</script>

  <style scoped>
  .el-icon{
    margin-right: 10px
  }
  </style>
